package com.sq.partner.manager.controller;

import java.math.BigDecimal;
import java.sql.Struct;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.sq.partner.manager.mybatis.model.GatewayMenu;
import org.apache.log4j.Logger;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.sq.partner.manager.common.Config;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.GatewayScanUnionCode;
import com.sq.partner.manager.service.UnionScanManagerService;
import com.sq.partner.manager.util.EncryptUtil;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.QRcodeUtil;
import com.sq.partner.manager.util.RuleEncryptUtil;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;

/**
 *
 *@author Wangsw
 */
@Controller
@RequestMapping(value = "/unionScanConfig")
public class UnionScanConfigController {

	private static Logger logger = LogUtil.getLog(ScanPolicyListController.class);

	@Resource
	private UnionScanManagerService unionScanManagerService;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String toListPage(){
		return "/unionScanManger/list";
	}




	/**
	 * @author
	 * @throws SQLException/Exception
	 * @param page
	 * @param partnerCode 合作伙伴代码
	 * @param unionScanQRCodeName 聚合二维码名称
	 * @return 根据条件查询出分页的聚合二维码信息，并返回前端
	 */
	@RequestMapping(value = "/queryUnionQRCodeListByPageNumber")
	@ResponseBody
	public Page<GatewayScanUnionCode> queryUnionQRCodeListByPageNumber(Page<GatewayScanUnionCode> page , String unionScanQRCodeName) throws Exception{
		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		paramMap.put("unionCodeName", unionScanQRCodeName==null?"":unionScanQRCodeName);
		page.setMap(paramMap);
		page = unionScanManagerService.queryUnionQRCodeListByPageNumber(page);
		int dataSize = unionScanManagerService.queryUnionCodeCountByConditions(page);
		if(dataSize%page.getSize() == 0){
			page.setMaxPage(dataSize/page.getSize());
		}else {
			page.setMaxPage(dataSize/page.getSize() +1 );
		}
		return page ;
	}


	@RequestMapping(value = "/edit")
	public String toEditUnionCodePage(ModelMap model ,String codeId) throws Exception{
		if(codeId == null ){
			return "参数错误";
		}
		//查询到菜单名，菜单描述
		try {
//		GatewayScanUnionCode uc = unionScanManagerService.querySingleUnionCodeById(Integer.parseInt(codeId));
			GatewayMenu menu = unionScanManagerService.querySingleMenuById(Integer.parseInt(codeId));
//		model.put("type", "edit");
			model.put("codeId", codeId);
			model.put("menuId", menu.getMenuid());
			model.put("menuName", menu.getMenuName());
			model.put("menuDesc", menu.getMenuDesc());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/unionScanManger/edit";
	}

	@RequestMapping(value = "/add")
	public String toAddUnionCodePage(ModelMap model){
		model.put("type", "add");
		return "/unionScanManger/add";
	}

	@RequestMapping(value = "/downloadQRCode")
	public void downloadQRCode( String ruleAgentId,HttpServletResponse response) throws Exception {
		/*//先查这个二维码
		GatewayScanUnionCode code = unionScanManagerService;
		//查二维码关联的菜单ID
		Integer menuId = code.getMenuId().intValue();
		//将其加密，作为参数拼接到URL中
		String idStr = RuleEncryptUtil.base64Encode(RuleEncryptUtil.encrypt(menuId.toString()));
		String picName=code.getUnionCodeName();*/
		String classPath=this.getClass().getResource("").getPath();
		String url = (classPath.substring(0,classPath.indexOf("/WEB-INF/")+8)+ "/images/logo.png").replace("/WEB-INF", "");
		QRcodeUtil.QRcodeToStream1(response, Config.getProp("JHEWM.URL")+ruleAgentId, "", "聚合二维码", 300, 300,url);
	}


	/**
	 * @since：2022年7月22日
	 * @description 查可配置的子二维码信息（分页）
	 * @param page
	 * @param menuId
	 * @param selectMenuName
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryScanMenu")
	@ResponseBody
	public Page<Map<String,Object>> queryScanMenu(Page<Map<String,Object>> page,String menuId,String selectMenuName) throws Exception{
		Map<String,Object> paramap = SqlUtil.buildPageMap(page);
		paramap.put("menuId", menuId);
		paramap.put("menuName", selectMenuName);
		page.setMap(paramap);
		page = unionScanManagerService.queryMenuCanBeConfigByPageNumber(page);
		int dataSize = unionScanManagerService.queryMenuCanBeCinfigCountByConditions(page);
		if(dataSize%page.getSize() == 0){
			page.setMaxPage(dataSize/page.getSize());
		}else {
			page.setMaxPage(dataSize/page.getSize() +1 );
		}
		return page ;
	}


	/**
	 * @since：2022年7月26日
	 * @description:分页查询已配置的二维码信息
	 * @param page
	 * @param ruleId
	 * @param agentId
	 * @param planNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryConfigedScanCode")
	@ResponseBody
	public Page<Map<String,Object>> queryConfigedScanCode(Page<Map<String,Object>> page,String ruleId,String agentId,String planNo) throws Exception{
		Map<String,Object> paramap = SqlUtil.buildPageMap(page);
		paramap.put("ruleId", ruleId);
		paramap.put("agentId", agentId);
		paramap.put("planNo", planNo);
		page.setMap(paramap);
		page = unionScanManagerService.queryConfigedUnionCodeByPage(page);
		int dataSize = unionScanManagerService.queryConfigedUnionCodeCountByPage(page);
		if(dataSize%page.getSize() == 0){
			page.setMaxPage(dataSize/page.getSize());
		}else {
			page.setMaxPage(dataSize/page.getSize() +1 );
		}
		page.setResult("success");
		return page;
	}


	/**
	 *
	 * @param page
	 * @param menuId
	 * @param menuName
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryConfigedMenu")
	@ResponseBody
	public Page<Map<String,Object>> queryConfigedMenu(Page<Map<String,Object>> page,String menuId,String menuName) throws Exception{
		Map<String,Object> paramap = SqlUtil.buildPageMap(page);
		paramap.put("menuId", menuId);
		paramap.put("menuName", menuName);
		page.setMap(paramap);
		page = unionScanManagerService.queryConfigedMenuByPage(page);
		int dataSize = unionScanManagerService.queryConfigedMenuCountByPage(page);
		if(dataSize%page.getSize() == 0){
			page.setMaxPage(dataSize/page.getSize());
		}else {
			page.setMaxPage(dataSize/page.getSize() +1 );
		}
		page.setResult("success");
		return page;
	}

	/**
	 * @since：2022年7月28日
	 * @description:删除某个已配置的二维码
	 * @param subMenuId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteMenuUnion")
	@ResponseBody
	public Result deleteMenuUnion(String subMenuId,String menuId) throws Exception{

		//删除前先判断该二级菜单下是否关联了方案，如果有，不可删除
		Integer count = unionScanManagerService.selectPlanCountByMenuId(subMenuId);
		if (count != 0){
			return Result.fail("请先删除该菜单下关联的方案");
		}

		unionScanManagerService.deleteMenuUnion(subMenuId);

		unionScanManagerService.checkAfterDelete(menuId,"M");
		return Result.success("删除成功");
	}

	/**
	 * @since：2022年7月29日
	 * @description：将子菜单关联至菜单上，初版中，menuId是固定的一级菜单。
	 * @param menuId
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/saveChecked")
	@ResponseBody
	public Result saveCheckedCodes(String menuId,String ids) throws Exception{
		if(ids == null){
			return Result.error("传入参数为空");
		}

		boolean flag = unionScanManagerService.checkBeforeAdd(menuId, "M");
		if (!flag){
			return Result.error("该菜单已关联方案，不可再关联子菜单");
		}

		//转数组
		String[] id = ids.split(",");
		boolean rs = unionScanManagerService.insertMenuRela(id, menuId);

		if(rs){
			return Result.success("关联成功");
		}else {
			return Result.error("关联过程中出现问题！");
		}
	}

	/**
	 * @since：2022年8月1日
	 * @description:	增加新的聚合二维码
	 * @param codeName
	 * @param codeDesc
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="addNewUnionCode")
	@ResponseBody
	public Result addNewUnionCode(String codeName,String codeDesc) throws Exception{
		Map<String,String> param = new HashMap<String, String>();
		param.put("codeName", codeName);
		param.put("codeDesc", codeDesc);
		if(codeName == null || codeName.length() == 0){
			return Result.error("二维码名称不可为空");
		}
		int rsId = unionScanManagerService.addNewUnionCode(param);
		if(rsId != 0){
			return Result.success("",rsId);
		}else {
			return Result.error("新增过程中出现问题！");
		}

	}


	/**
	 * 更新菜单名以及菜单描述
	 * @param codeId
	 * @param menuName
	 * @param menuDesc
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="updateNewMenu")
	@ResponseBody
	public Result updateNewMenu(String codeId,String menuName,String menuDesc) throws Exception{
		Map<String,String> param = new HashMap<String, String>();
		param.put("codeId", codeId);
		param.put("menuName", menuName);
		param.put("menuDesc", menuDesc);
		if (codeId == null || codeId.length() == 0){
			return Result.error("系统异常，请联系管理员");
		}
		if(menuName == null || menuName.length() == 0){
			return Result.error("二维码名称不可为空");
		}
		boolean rs = unionScanManagerService.updateNewMenu(param);
		if(rs){
			return Result.success("更新成功",codeId);
		}else {
			return Result.error("更新过程中出现问题！");
		}

	}

	@RequestMapping(value="/deleteUnionCode")
	@ResponseBody
	public Result deleteUnionCode(String codeId) throws Exception{

		if(codeId == null ){
			return  Result.fail();
		}

		//删除二维码前先判断该二维码对应的菜单下是否关联了方案或二级菜单，如果有，不可删除
		Integer planCount = unionScanManagerService.selectPlanCountByUnionCode(codeId);
		Integer menuCount = unionScanManagerService.selectMenuCountByUnionCode(codeId);
		if (planCount != 0){
			return Result.fail("请先删除该菜单下关联的方案");
		}else if (menuCount != 0){
			return Result.fail("请先删除该菜单下关联的二级菜单");
		}


		//这里还需要删除与二维码绑定的一级菜单
		boolean deleteMenuFlag = unionScanManagerService.deleteMenuByUnionCode(codeId);
		boolean deleteUnionCodeFlag = unionScanManagerService.deleteUnionCode(codeId);
		if(deleteUnionCodeFlag){
			return Result.success("删除成功");
		}

		return Result.fail();
	}
}
